之前沒用過這個模式,目前的理解是相似的物件就不用一直 new,感覺很方便
public class Member {
private String name;
private String age;
...
}
public class Computer {
private String brand;
}
public class Computer implements Cloneable {
private String brand;
@NonNull
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
public class Member {
private String name;
private String age;
private Computer computer;
...
}
public class Member implements Cloneable {
...
@NonNull
@Override
public Member clone() throws CloneNotSupportedException{
Member clone = new Member(this.computer);
clone.setName(this.name);
clone.setAge(this.age);
return clone;
}
public Member(Computer computer) throws CloneNotSupportedException {
this.computer = (Computer) computer.clone();
}
}
Member memberBase = new Member();
memberBase.setName("AndyAWD");
memberBase.setAge("30");
Computer computer = new Computer();
computer.setBrand("ASUS");
memberBase.setComputer(computer);
Member member1 = memberBase.clone();
Computer computer1 = new Computer();
computer1.setBrand("APPLE");
member1.setComputer(computer1);
Member member2 = member.clone();
Computer computer2 = new Computer();
computer2.setBrand("MSI");
member2.setComputer(computer2);
基本角色 - 姓名:AndyAWD / 年齡:30 / 電腦品牌:ASUS
會員1 - 姓名:AndyAWD / 年齡:30 / 電腦品牌:APPLE
會員2 - 姓名:AndyAWD / 年齡:30 / 電腦品牌:MSI